package top.mcwebsite.playandroid.lib.mvi.base

import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import top.mcwebsite.playandroid.lib.common.Tuple
import kotlin.reflect.KProperty1


fun <A, I: IIntent, U: IUiState, E: IUiEffect, VM: BaseViewModel<I, U, E>> VM.internalSubscribe(
    lifecycleOwner: LifecycleOwner?,
    prop1: KProperty1<U, A>,
    block: suspend (A) -> Unit,
) {
    uiStateFlow
        .map { Tuple(prop1.get(it)) }
        .distinctUntilChanged()
        .subscription(lifecycleOwner) {
            block(it.a)
        }
}


fun <A, B, I: IIntent, U: IUiState, E: IUiEffect, VM: BaseViewModel<I, U, E>> VM.internalSubscribe(
    lifecycleOwner: LifecycleOwner?,
    prop1: KProperty1<U, A>,
    prop2: KProperty1<U, B>,
    block: suspend (A, B) -> Unit,
) {
    uiStateFlow
        .map { Tuple(prop1.get(it), prop2.get(it)) }
        .distinctUntilChanged()
        .subscription(lifecycleOwner) {
            block(it.a, it.b)
        }
}